package com.firstresponder.activity;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.IBinder;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.SystemClock;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.Toast;
import android.widget.Chronometer.OnChronometerTickListener;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.firstresponder.bluetooth.BluetoothService;
import com.firstresponder.location.LocationService;
import com.firstresponder.location.LocationService.LocalBinder;
import com.firstresponder.util.MessageSender;
import com.firstresponder.util.SmsReceiver;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

/**
 * This class handles all the UI events and any visuals you might see.
 * 
 * @author Jessicardo
 * 
 */
public class FirstResponder extends MapActivity {

	private static final String TAG = "FirstResponder";
	private boolean isFlipped = false;
	private ArrayList<String> reverseGeocodeAddress;
	private ArrayList<String> textDirections;
	private long startTime;
	private long pausedTime;
	private long countUp;
	private long saveBaseTime;
	private LinearLayout tabLayout, directionsL, alertDescriptionLayout;
	private MapView mapview;
	LocationListener loclis;
	static final int MIN_TIME_INTERVAL_BETWEEN_NOTIFICATIONS = 20000;
	static final int MIN_CHANGE_IN_DISTANCE_BETWEEN_NOTIFICATIONS = 100;
	MessageSender MESSAGE_SENDER = MessageSender.getInstance();
	// *****items needed for adding markers to the map********
	List<Overlay> mapOverlays;
	Drawable drawableStart, drawableStop, drawableMov;
	Location location;
	private MapController myMC = null;
	private GeoPoint geoPoint = null;
	// ****UI variables for this class starts here******
	private MediaPlayer mp, mp2;
	private ViewFlipper screen, routeScreen, apparatusScreenManager;
	private Button respondingButton;
	private Button notRespondingButton;
	private Button alertTab, routeTab, apparatusTab, prePlanTab, adminTab,
			mapTab, directionsTab, turnTab, refreshTab,
			seeBluetoothScanningScreen, assetsButton;
	private TextView statusText, alertTimer;
	// *****other utility variables*******
	private boolean resButtonStatus = false;
	private boolean notResButtonStatus = false;
	private ExpandableListAdapter adminAdapter, apparatusAdapter;
	private ExpandableListView adminExpandableListView,
			apparatusExpandableListView;
	private int greenishBackgroundColor = 0xFF012C07;
	private int greenishColor = 0xFF0F9521;
	private int blackishColor = Color.BLACK;
	private ProgressDialog dialog2;
	// **********for OnsavedInstance********
	private int[] tabColor = { greenishBackgroundColor, greenishColor,
			greenishColor, greenishColor, greenishColor, blackishColor,
			blackishColor, Color.DKGRAY, greenishBackgroundColor,
			greenishBackgroundColor };
	private WebView webView;
	// *****BluetoothScreen Declarations*******
	private String bTAG = "BLUETOOTHSERVICE TEST";
	private static final int ADDR_MSG_TYPE = 0;
	private static final int ALERT_MSG_TYPE = 1;
	private static final int WAIT_MSG_TYPE = 2;
	private boolean buttonStatus = false;
	private BluetoothAdapter TestAdapter;
	private ProgressDialog dialog = null;
	private Intent blueserviceintent = null;
	private TextView TitleText, TimerText, NumDeviceText;
	private ArrayList<String> textViewList = null;
	private ViewGroup linearlayout, bottom_layout;
	private Button stopButton;
	// *****Timer object******
	private Chronometer stopWatch;

	private LocationService mService;
	boolean mBound = false;
	Intent locationServiceIntent = null;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.all_screens);

		// THIS IS FOR TESTING
		if (LocationService.getServiceStatus() != LocationService.ALERT_MODE) {
			locationServiceIntent = new Intent(this, LocationService.class);
			LocationService.setServiceStatus(LocationService.ALERT_MODE);
			startService(locationServiceIntent);
		}
		// END TESTING

		// ******Initialization of map view items*******
		mapview = (MapView) findViewById(R.id.map_view);
		mapview.setBuiltInZoomControls(true);
		mapview.setSatellite(false);
		// *************Initialization of UI Items*************
		screen = (ViewFlipper) findViewById(R.id.screenManager);
		routeScreen = (ViewFlipper) findViewById(R.id.routeScreenManager);
		apparatusScreenManager = (ViewFlipper) findViewById(R.id.apparatusScreenManager);
		respondingButton = (Button) findViewById(R.id.respondingButton);
		notRespondingButton = (Button) findViewById(R.id.notRespondingButton);
		statusText = (TextView) findViewById(R.id.statusText);
		routeTab = (Button) findViewById(R.id.routeTab);
		apparatusTab = (Button) findViewById(R.id.apparatusTab);
		prePlanTab = (Button) findViewById(R.id.prePlanTab);
		adminTab = (Button) findViewById(R.id.adminTab);
		alertTab = (Button) findViewById(R.id.alertTab);
		mapTab = (Button) findViewById(R.id.mapTab);
		directionsTab = (Button) findViewById(R.id.directionsTab);
		turnTab = (Button) findViewById(R.id.turnTab);
		refreshTab = (Button) findViewById(R.id.refreshTab);
		directionsL = (LinearLayout) findViewById(R.id.directionsL);
		seeBluetoothScanningScreen = (Button) findViewById(R.id.seeBluetoothScanningButton);
		assetsButton = (Button) findViewById(R.id.assetsLayout);
		alertDescriptionLayout = (LinearLayout) findViewById(R.id.alertDescriptionLayout);
		tabLayout = (LinearLayout) findViewById(R.id.TabLayout);
		// ***********BluetoothScreen ids *********************
		textViewList = new ArrayList<String>();
		View layout = findViewById(R.id.linear_layout);
		linearlayout = (ViewGroup) layout;
		layout = findViewById(R.id.bottom_layout);
		bottom_layout = (ViewGroup) layout;
		TitleText = (TextView) findViewById(R.id.log_title);
		TimerText = (TextView) findViewById(R.id.timer_text);
		TimerText.setTextColor(Color.YELLOW);
		NumDeviceText = (TextView) findViewById(R.id.num_device_text);
		NumDeviceText.setTextColor(Color.GREEN);
		stopButton = (Button) findViewById(R.id.stopButton);
		// **********setting up the expandable list view for apparatus and
		// admin*******
		adminExpandableListView = (ExpandableListView) findViewById(R.id.adminExpandableListView);
		apparatusExpandableListView = (ExpandableListView) findViewById(R.id.apparatusExpandableListView);
		stopWatch = (Chronometer) findViewById(R.id.chrono);
		alertTimer = (TextView) findViewById(R.id.alertTimer);
		// **********WebView object id***************
		webView = (WebView) findViewById(R.id.webView);

		// setters and declarations
		MyExpandableAdminListAdapter.setMainActivity(this);
		MyExpandableApparatusListAdapter.setMainActivity(this);
		DirectionPathOverlay.setMainActivity(this);
		stopButton.setTextColor(Color.RED);
		reverseGeocodeAddress = new ArrayList<String>();

		adminAdapter = new MyExpandableAdminListAdapter();
		apparatusAdapter = new MyExpandableApparatusListAdapter();

		adminExpandableListView.setAdapter(adminAdapter);
		apparatusExpandableListView.setAdapter(apparatusAdapter);

		respondingButton.getBackground().setColorFilter(0xFF00FF00,
				PorterDuff.Mode.MULTIPLY);
		respondingButton.setTextColor(Color.WHITE);
		notRespondingButton.getBackground().setColorFilter(0xFFFF0000,
				PorterDuff.Mode.MULTIPLY);
		notRespondingButton.setTextColor(Color.WHITE);
		turnTab.getBackground().setColorFilter(Color.DKGRAY,
				PorterDuff.Mode.MULTIPLY);
		turnTab.setTextColor(Color.WHITE);
		refreshTab.getBackground().setColorFilter(Color.DKGRAY,
				PorterDuff.Mode.MULTIPLY);
		refreshTab.setTextColor(Color.WHITE);
		// externalNavButton.getBackground().setColorFilter(0xFFD51717,
		// PorterDuff.Mode.MULTIPLY);
		// externalNavButton.setTextColor(Color.WHITE);
		// Elaspsed time configuration
		// ********************listeners*******************
		stopWatch.setOnChronometerTickListener(new OnChronometerTickListener() {
			@Override
			public void onChronometerTick(Chronometer arg0) {
				if (!isFlipped) {// saves starting current starting time so
									// when the phone is flipped it doesn't
									// restart
					saveBaseTime(arg0.getBase());
				}
				countUp = (SystemClock.elapsedRealtime() - saveBaseTime) / 1000;

                                if (countUp % 60 < 10) {
                                        // properly formats the counter when seconds is below 10
                                        String asText = "+" + (countUp / 60) + ":" + "0"
                                                        + (countUp % 60);
                                        alertTimer.setText(asText);
                                } else {
                                        String asText = "+" + (countUp / 60) + ":" + (countUp % 60);
                                        alertTimer.setText(asText);
                                }
                        }
                });
                stopWatch.start();
                adminExpandableListView
                                .setOnGroupClickListener(new OnGroupClickListener() {
                                        @Override
                                        public boolean onGroupClick(ExpandableListView arg0,
                                                        View arg1, int groupPosition, long arg3) {
                                                if (groupPosition == 5) {
                                                }
                                                return false;
                                        }
                                });
                adminExpandableListView
                                .setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
                                        @Override
                                        public boolean onChildClick(ExpandableListView parent,
                                                        View v, int groupPosition, int childPosition,
                                                        long id) {
                                                return false;
                                        }
                                });
               // adminExpandableListView.expandGroup(2);// make the "Bluetooth" list
               // dropped down by default.
               //****NOTE: This method was causing the getChildView() functions in the 
               //respective adapters to get called infinitely.
                apparatusExpandableListView
                                .setOnGroupClickListener(new OnGroupClickListener() {
                                        @Override
                                        public boolean onGroupClick(ExpandableListView arg0,
                                                        View arg1, int groupPosition, long arg3) {
                                                if (groupPosition == 5) {

                                                }
                                                return false;
                                        }
                                });
                // make the "Apparatus" list dropped down by default.
              //  apparatusExpandableListView.expandGroup(2);
              //****NOTE: This method was causing the getChildView() functions in the 
                //respective adapters to get called infinitely.
                apparatusExpandableListView
                                .setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
                                        @Override
                                        public boolean onChildClick(ExpandableListView parent,
                                                        View v, int groupPosition, int childPosition,
                                                        long id) {
                                                return false;
                                        }
                                });
                this.respondingButton.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                                try {
                                        if (!resButtonStatus) {
                                                mService.cancelInference();
                                                MESSAGE_SENDER.sendYesResponseMessage("YES");
                                                mp = MediaPlayer.create(FirstResponder.this,
                                                                R.raw.responding);
                                                mp.start();// output audio "responding"
                                                respondingButton.getBackground().setColorFilter(
                                                                0xFFC6FFC6, PorterDuff.Mode.MULTIPLY);
                                                notRespondingButton.getBackground().setColorFilter(
                                                                0xFFFF0000, PorterDuff.Mode.MULTIPLY);
                                                setResButtonStatus(true);
                                                setNotResButtonStatus(false);
                                                statusText.setText("RESPONDING");
                                                // pause for 1 second before switching tab automatically
                                                // to
                                                // allow audio to play before releasing
                                                // the audio object.
                                                Handler handler = new Handler();
                                                handler.postDelayed(new Runnable() {
                                                        public void run() {
                                                                releaseMp();// failure to call this
                                                                                        // method immediately if
                                                                                        // a MediaPlayer object
                                                                                        // is no longer needed
                                                                                        // may
                                                                // also lead to continuous battery
                                                                // consumption for mobile devices,
                                                                // and playback failure if no
                                                                // multiple instances of the same
                                                                // codec is supported on a device.
                                                                screen.setDisplayedChild(2);
                                                                resetTabColors();
                                                                routeTab.setBackgroundColor(Color.DKGRAY);
                                                                mapTab.setBackgroundColor(blackishColor);
                                                                tabLayout.setBackgroundColor(Color.DKGRAY);
                                                                tabColor[2] = Color.DKGRAY;
                                                                tabColor[5] = blackishColor;
                                                                tabColor[7] = Color.DKGRAY;
                                                                // no need for external map as i
                                                                // have added a mapview functionality
                                                                // still, code is left here just in case this
                                                                // might
                                                                // be needed.
                                                                // Intent intent = new
                                                                // Intent(android.content.Intent.ACTION_VIEW,
                                                                // Uri.parse("http://maps.google.com/maps?saddr=40.7221,-73.7904&daddr=40.7144,-73.7899"))
                                                                // .setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                                                                // intent.setClassName(
                                                                // "com.google.android.apps.maps",
                                                                // "com.google.android.maps.MapsActivity");
                                                                // startActivity(intent);
                                                        }
                                                }, 1000);
                                        }
                                } catch (Throwable t) {
                                        Log.e(TAG, Log.getStackTraceString(t));
                                }
                        }
                });
                this.notRespondingButton.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                                try {
                                        if (!notResButtonStatus) {
                                                mService.cancelInference();
                                                MESSAGE_SENDER.sendNoResponseMessage("NO");
                                                // output audio "not responding"
                                                mp2 = MediaPlayer.create(FirstResponder.this,
                                                                R.raw.not_responding);
                                                mp2.start();
                                                notRespondingButton.getBackground().setColorFilter(
                                                                0xFFFF8D8D, PorterDuff.Mode.MULTIPLY);
                                                respondingButton.getBackground().setColorFilter(
                                                                0xFF00FF00, PorterDuff.Mode.MULTIPLY);
                                                setNotResButtonStatus(true);
                                                setResButtonStatus(false);
                                                statusText.setText("NOT RESPONDING");
                                                // pause for 1 second before switching tab automatically
                                                // to
                                                // allow audio to play before releasing
                                                // the audio object.
                                                Handler handler = new Handler();
                                                handler.postDelayed(new Runnable() {
                                                        public void run() {
                                                                releaseMp2();// failure to call this
                                                                                                // method
                                                                                                // immediately if a
                                                                                                // MediaPlayer
                                                                                                // object is no
                                                                                                // longer needed may
                                                                // also lead to continuous battery
                                                                // consumption for mobile devices,
                                                                // and playback failure if no
                                                                // multiple instances of the same
                                                                // codec is supported on a device.
                                                                screen.setDisplayedChild(1);
                                                                resetTabColors();
                                                                apparatusTab
                                                                                .setBackgroundColor(greenishBackgroundColor);
                                                                tabColor[1] = greenishBackgroundColor;
                                                                // when not responding, we go to the apparatus
                                                                // status tab instead
                                                        }
                                                }, 1000);

					}
				} catch (Throwable t) {
					Log.e(TAG, Log.getStackTraceString(t));
				}
			}
		});
		this.alertTab.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					screen.setDisplayedChild(5);
					resetTabColors();
					tabColor[0] = greenishBackgroundColor;
					alertTab.setBackgroundColor(greenishBackgroundColor);
				} catch (Throwable t) {
					Log.e(TAG, Log.getStackTraceString(t));
				}
			}
		});
		this.routeTab.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					screen.setDisplayedChild(2);
					resetTabColors();
					tabColor[2] = Color.DKGRAY;
					if (routeScreen.getDisplayedChild() != 1) {
						tabColor[5] = blackishColor;
						mapTab.setBackgroundColor(blackishColor);
					} else if (routeScreen.getDisplayedChild() == 1) {
						directionsTab.setBackgroundColor(blackishColor);
						tabColor[6] = blackishColor;
					}

					tabColor[7] = Color.DKGRAY;
					routeTab.setBackgroundColor(Color.DKGRAY);
					tabLayout.setBackgroundColor(Color.DKGRAY);
				} catch (Throwable t) {
					Log.e(TAG, Log.getStackTraceString(t));
				}
			}
		});
		this.apparatusTab.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					screen.setDisplayedChild(1);
					resetTabColors();
					if (apparatusScreenManager.getDisplayedChild() != 1) {
						tabColor[9] = blackishColor;// save assets button tab
													// color
						assetsButton.setBackgroundColor(blackishColor);
					} else if (apparatusScreenManager.getDisplayedChild() == 1) {
						tabColor[8] = blackishColor;
						seeBluetoothScanningScreen
								.setBackgroundColor(blackishColor);
					}
					tabColor[1] = greenishBackgroundColor;// save aparatus
															// tab/assets tab
															// color
					apparatusTab.setBackgroundColor(greenishBackgroundColor);
				} catch (Throwable t) {
					Log.e(TAG, Log.getStackTraceString(t));
				}
			}
		});
		this.prePlanTab.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					screen.setDisplayedChild(3);
					resetTabColors();
					tabColor[3] = greenishBackgroundColor;
					prePlanTab.setBackgroundColor(greenishBackgroundColor);
				} catch (Throwable t) {
					Log.e(TAG, Log.getStackTraceString(t));
				}
			}
		});
		this.adminTab.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					screen.setDisplayedChild(4);
					resetTabColors();
					tabColor[4] = greenishBackgroundColor;
					adminTab.setBackgroundColor(greenishBackgroundColor);
				} catch (Throwable t) {
					Log.e(TAG, Log.getStackTraceString(t));
				}
			}
		});
		this.mapTab.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					routeScreen.setDisplayedChild(3);
					resetTabColors();
					tabColor[5] = blackishColor;
					tabColor[2] = Color.DKGRAY;
					routeTab.setBackgroundColor(Color.DKGRAY);
					mapTab.setBackgroundColor(blackishColor);
					tabColor[7] = Color.DKGRAY;
					tabLayout.setBackgroundColor(Color.DKGRAY);
				} catch (Throwable t) {
					Log.e(TAG, Log.getStackTraceString(t));
				}
			}
		});
		this.directionsTab.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					routeScreen.setDisplayedChild(1);
					resetTabColors();
					tabColor[6] = blackishColor;
					tabColor[2] = Color.DKGRAY;
					routeTab.setBackgroundColor(Color.DKGRAY);
					tabColor[7] = Color.DKGRAY;
					tabLayout.setBackgroundColor(Color.DKGRAY);
					directionsTab.setBackgroundColor(blackishColor);
				} catch (Throwable t) {
					Log.e(TAG, Log.getStackTraceString(t));
				}
			}
		});
		this.turnTab.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {

					Intent intent = new Intent(
							android.content.Intent.ACTION_VIEW,
							Uri.parse("google.navigation:q=40.7144,-73.7899"))
							.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
					startActivity(intent);
				} catch (Throwable t) {
					Log.e(TAG, Log.getStackTraceString(t));
				}
			}
		});
		this.refreshTab.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					if ((mService.getCurrGpsLocation() != null)
							&& (mService.getCurrDestination() != null)) {
						Log.i(TAG,
								"GPS and Destination Received... Drawing Map");
						Location loc = mService.getCurrGpsLocation();
						Location des = mService.getCurrDestination();
						populateMapAndGetDirections(loc, des);

					}
				} catch (Throwable t) {
					Log.e(TAG, Log.getStackTraceString(t));
				}
			}
		});
		this.seeBluetoothScanningScreen
				.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						try {
							apparatusScreenManager.setDisplayedChild(1);
							resetTabColors();
							tabColor[1] = greenishBackgroundColor;// save
																	// aparatus
																	// tab/assets
																	// tab color
							tabColor[8] = blackishColor;
							apparatusTab
									.setBackgroundColor(greenishBackgroundColor);
							seeBluetoothScanningScreen
									.setBackgroundColor(blackishColor);
						} catch (Throwable t) {
							Log.e(TAG, Log.getStackTraceString(t));
						}
					}
				});
		this.assetsButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					apparatusScreenManager.setDisplayedChild(2);
					resetTabColors();
					tabColor[1] = greenishBackgroundColor;// save aparatus
															// tab/assets tab
															// color
					tabColor[9] = blackishColor;// save assets button tab color
					apparatusTab.setBackgroundColor(greenishBackgroundColor);
					assetsButton.setBackgroundColor(blackishColor);
				} catch (Throwable t) {
					Log.e(TAG, Log.getStackTraceString(t));
				}
			}
		});
		// this.externalNavButton.setOnClickListener(new OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// Intent intent = new
		// Intent(android.content.Intent.ACTION_VIEW,
		// Uri.parse("http://maps.google.com/maps?saddr=40.7221,-73.7904&daddr=40.7144,-73.7899"))
		// .setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
		// intent.setClassName(
		// "com.google.android.apps.maps",
		// "com.google.android.maps.MapsActivity");
		// startActivity(intent);
		// }
		// });
		// Get the location manager
		// locationManager = (LocationManager)
		// getSystemService(Context.LOCATION_SERVICE);
		// Criteria criteria = new Criteria();
		// criteria.setAccuracy(Criteria.NO_REQUIREMENT);
		// criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
		// bestProvider = locationManager.getBestProvider(criteria, true);
		// location = locationManager.getLastKnownLocation(bestProvider);
		stopButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					if (!buttonStatus) {
						stopButton.setTextColor(Color.BLUE);
						Log.i(bTAG, "Service About to stop");
						stopButton.setText("RESTART");
						stopService(blueserviceintent);
						Toast.makeText(FirstResponder.this, "SERVICE STOPPED",
								Toast.LENGTH_SHORT).show();
						TimerText.setText("0");
						Log.i(bTAG, "Service Stopped");
						buttonStatus = true;
					} else {
						stopButton.setTextColor(Color.RED);
						stopButton.setText("STOP");
						startService(blueserviceintent);
						Toast.makeText(FirstResponder.this,
								"SERVICE RESTARTED", Toast.LENGTH_SHORT).show();
						buttonStatus = false;
					}
				} catch (Throwable t) {
					Log.e(TAG, Log.getStackTraceString(t));
				}
			}
		});
		// ********Bluetooth Service Screen items********
		blueserviceintent = new Intent(this, BluetoothService.class);
		TestAdapter = BluetoothAdapter.getDefaultAdapter();
		if (TestAdapter == null) {
			Log.i(bTAG, "This is not a Bluetooth capable device");
		} else {
			if (!TestAdapter.isEnabled()) {
				// Wait until adapter is fully enabled before starting service
				waitForEnable();
				Log.i(bTAG, "Bluetooth enabled");
			}
			try {
				Log.i(bTAG, "Service is about to get activated");
				BluetoothService.setMainActivity(this);
				// Orginally bind the test bluetoothScreen Activity to the
				// service
				// SmsReceiver.setMainActivity(this);
				MyExpandableAdminListAdapter.setMacAddress(TestAdapter
						.getAddress());
				TitleText.append(TestAdapter.getAddress());
				if (BluetoothService.isRunning() == false) {
					Log.i(bTAG, "STARTING SERVICE");
					startService(blueserviceintent);
					BluetoothService.setIsRunning(true);
					Log.i(bTAG, "SERVICE IS ACTIVATED");
				} else if (!TestAdapter.isDiscovering()) {
					UpdateUI("Waiting for Next Discovery Period...", 2);
				}
			} catch (Throwable t) {
				Log.e(TAG, Log.getStackTraceString(t));
			}
		}

		try {
			webView.getSettings().setJavaScriptEnabled(true);
			webView.loadUrl("http://first-responder.appspot.com");
			webView.setWebViewClient(new HelloWebViewClient());
		} catch (Throwable t) {
			Log.e(TAG, Log.getStackTraceString(t));
		}
		// webView.setHttpAuthUsernamePassword(host, realm, username, password)

		// Setting up the map.
		mapOverlays = mapview.getOverlays();

	}

	private PropertyChangeListener mapListener = new PropertyChangeListener() {
		@Override
		public void propertyChange(PropertyChangeEvent e) {
			Log.i(TAG, "PropertyChanged event Triggered");
			try {
				if ((mService.getCurrGpsLocation() != null)
						&& (mService.getCurrDestination() != null)) {
					Log.i(TAG, "GPS and Destination Received... Drawing Map");
					Location loc = mService.getCurrGpsLocation();
					Location des = mService.getCurrDestination();
					populateMapAndGetDirections(loc, des);
				}
			} catch (Throwable t) {
				Log.e(TAG, Log.getStackTraceString(t));
			}
		}
	};

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		// Bind to LocalService
		Intent ServiceIntent = new Intent(this, LocationService.class);
		bindService(ServiceIntent, mConnection, 0);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.fr_menu, menu);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case R.id.fr_prefs:
			Intent intent = new Intent(getApplicationContext(),
					FirstResponderPrefs.class);
			startActivity(intent);
			return true;
		default:
			return super.onMenuItemSelected(featureId, item);
		}
	}

	/** Register for the updates when Activity is in foreground */
	@Override
	protected void onResume() {
		super.onResume();
	}

	/** Stop the updates when Activity is paused */
	@SuppressWarnings("unchecked")
	@Override
	protected void onPause() {
		super.onPause();
		if (textViewList == null) {
			Log.i(TAG, "SAVED TEXT VIEW IS NULL onPause");
		}
		Log.i(TAG, "onPause() End");
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		try {
			SmsReceiver.setMainActivity(null);
			// Unbind from the service
			stopService(blueserviceintent);
			BluetoothService.setMainActivity(null);
			if (mBound) {
				Log.i(TAG, "CLOSING SERVICE CONNECTION");
				unbindService(mConnection);
				mService.removeChangeListener(mapListener);
				mBound = false;
			}
		} catch (Throwable t) {
			Log.e(TAG, Log.getStackTraceString(t));
		}
	}

	private ServiceConnection mConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName className, IBinder service) {
			// We've bound to LocalService, cast the IBinder and get
			// LocalService instance
			Log.i(TAG, "MAKING CONNECTION");
			LocalBinder binder = (LocalBinder) service;
			mService = binder.getService();
			mBound = true;
			mService.addChangeListener(mapListener);
			if (mService.getCurrDestination() != null) {
				Log.i(TAG, "THIS IS NOT NULL");
				Log.i(TAG, " LAT "
						+ mService.getCurrDestination().getLatitude());
				Log.i(TAG, " LONG "
						+ mService.getCurrDestination().getLongitude());
			}
			TextView geoAddressView = new TextView(FirstResponder.this);
			geoAddressView.setText(mService.reverseGeoCode(mService
					.getCurrDestination()));
			alertDescriptionLayout.addView(geoAddressView, 0);
			int count = alertDescriptionLayout.getChildCount();
			if (count > 1)
				alertDescriptionLayout.removeViewAt(count - 1);

			// gets the destination object(Location) and pass it in the
			// printAddress method that
			// reverse geocodes it and returns the TextView.

		}

		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			mBound = false;
		}
	};

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	// alerts the user and lets the user know that if they press "back" the
	// application will be destroyed.
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if (screen.getDisplayedChild() != 3) {
			AlertDialog.Builder dialog = new AlertDialog.Builder(this);
			dialog.setTitle("EXIT");
			dialog.setMessage("Leaving will DESTROY this app and all processes?");
			dialog.setPositiveButton("LEAVE",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							Intent locationServiceIntent = new Intent(
									FirstResponder.this, LocationService.class);
							LocationService
									.setServiceStatus(LocationService.PASSIVE_MODE);
							startService(locationServiceIntent);
							finish();
							overridePendingTransition(0, 0);
							FirstResponder.super.onBackPressed();
						}
					});
			dialog.setNeutralButton("STAY!",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.dismiss();
						}
					});
			dialog.show();
		} else {
			webView.goBack();
		}
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onRestoreInstanceState(savedInstanceState);
		// alertTimer.setText(savedInstanceState.getString("alertTimer"));

		isFlipped = savedInstanceState.getBoolean("isFlipped");
		screen.setDisplayedChild(savedInstanceState.getInt("screenM"));
		routeScreen
				.setDisplayedChild(savedInstanceState.getInt("routeScreenM"));
		apparatusScreenManager.setDisplayedChild(savedInstanceState
				.getInt("apparatusScreenM"));
		if (savedInstanceState.getBoolean("resButtonStatus") != false) {
			respondingButton.getBackground().setColorFilter(0xFFC6FFC6,
					PorterDuff.Mode.MULTIPLY);
			notRespondingButton.getBackground().setColorFilter(0xFFFF0000,
					PorterDuff.Mode.MULTIPLY);
			setResButtonStatus(true);
			setNotResButtonStatus(false);
			statusText.setText("Responding");
		} else if (savedInstanceState.getBoolean("notResButtonStatus") != false) {
			notRespondingButton.getBackground().setColorFilter(0xFFFF8D8D,
					PorterDuff.Mode.MULTIPLY);
			respondingButton.getBackground().setColorFilter(0xFF00FF00,
					PorterDuff.Mode.MULTIPLY);
			setNotResButtonStatus(true);
			setResButtonStatus(false);
			statusText.setText("Not Responding");
		}
		alertTab.setBackgroundColor(savedInstanceState.getIntArray("tabColors")[0]);
		routeTab.setBackgroundColor(savedInstanceState.getIntArray("tabColors")[2]);
		apparatusTab.setBackgroundColor(savedInstanceState
				.getIntArray("tabColors")[1]);
		prePlanTab.setBackgroundColor(savedInstanceState
				.getIntArray("tabColors")[3]);
		adminTab.setBackgroundColor(savedInstanceState.getIntArray("tabColors")[4]);
		mapTab.setBackgroundColor(savedInstanceState.getIntArray("tabColors")[5]);
		directionsTab.setBackgroundColor(savedInstanceState
				.getIntArray("tabColors")[6]);
		tabLayout.setBackgroundColor(savedInstanceState
				.getIntArray("tabColors")[7]);
		seeBluetoothScanningScreen.setBackgroundColor(savedInstanceState
				.getIntArray("tabColors")[8]);
		assetsButton.setBackgroundColor(savedInstanceState
				.getIntArray("tabColors")[9]);

		tabColor = savedInstanceState.getIntArray("tabColors");// update current
																// arraylist

		NumDeviceText.setText(savedInstanceState.getString("deviceCount"));
		TimerText.setText(savedInstanceState.getString("timerText"));
		ArrayList<String> savedTextList = savedInstanceState
				.getStringArrayList("textViews");
		for (String text : savedTextList) {
			UpdateUI(text, ADDR_MSG_TYPE);
		}

		saveBaseTime = savedInstanceState.getLong("saveBaseTime");
		for (int i = 0; i < savedInstanceState
				.getInt("reverseGeocodeAddressSize"); i++) {
			// add back all values to the arrayList.
			reverseGeocodeAddress.add(savedInstanceState.getString(i
					+ "reverseGeocodeAddress"));
		}
		try {
			if (savedInstanceState.containsKey("textDirections")) {
				// trying to save text directions when phone is flipped
				ListView listview1 = new ListView(this);
				ArrayList<String> textDirections = savedInstanceState
						.getStringArrayList("textDirections");
				Log.i(TAG, "COUNT:" + textDirections.size());
				listview1.setAdapter(new ArrayAdapter<String>(
						FirstResponder.this,
						android.R.layout.simple_list_item_1, savedInstanceState
								.getStringArrayList("textDirections")));
				AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
						ViewGroup.LayoutParams.FILL_PARENT, 600);
				listview1.setLayoutParams(lp);
				if (directionsL.getChildCount() == 1) {
					directionsL.removeViewAt(0);
				}
				directionsL.addView(listview1, 0);
			}
		} catch (Throwable t) {
			Log.e(TAG, Log.getStackTraceString(t));
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putBoolean("isFlipped", true);
		outState.putInt("screenM", screen.getDisplayedChild());
		outState.putInt("routeScreenM", routeScreen.getDisplayedChild());
		outState.putInt("apparatusScreenM",
				apparatusScreenManager.getDisplayedChild());
		outState.putBoolean("resButtonStatus", resButtonStatus);
		outState.putBoolean("notResButtonStatus", notResButtonStatus);
		outState.putIntArray("tabColors", tabColor);
		if (textDirections != null) {
			// trying to save the text directions when the phone is flipped
			outState.putStringArrayList("textDirections", textDirections);
		}
		outState.putLong("saveBaseTime", saveBaseTime);
		outState.putString("deviceCount", (String) NumDeviceText.getText());
		outState.putString("timerText", (String) TimerText.getText());
		for (int i = 0; i < reverseGeocodeAddress.size(); i++) {
			outState.putString(i + "reverseGeocodeAddress",
					reverseGeocodeAddress.get(i));
		}
		outState.putInt("reverseGeocodeAddressSize",
				reverseGeocodeAddress.size());
		// for (TextView view : textViewList) {
		// Log.i(TAG, "REMOVING VIEW FROM LAYOUT");
		// linearlayout.removeView(view);
		// }
		if (textViewList == null) {
			Log.i(TAG, "SAVED TEXT VIEW IS NULL");
		}
		outState.putStringArrayList("textViews", textViewList);
		Log.i(TAG, "End onSavedInstanceState();");
		super.onSaveInstanceState(outState);
	}

	// ******************************************Cycle methods ended, Other
	// methods below***************************
	public void UpdateUI(String text, int type) {
		try {
			Log.i(bTAG, "Appending Text");
			TextView logText = new TextView(getBaseContext());
			logText.append("Log: " + text + "\n");
			if (type == ALERT_MSG_TYPE) {
				logText.setTextColor(Color.RED);
			} else if (type == WAIT_MSG_TYPE) {
				logText.setTextColor(Color.GREEN);
			}
			linearlayout.addView(logText, 1);
			Log.i(bTAG, "LinearLayout size " + linearlayout.getChildCount());
			if (textViewList.size() <= 12) {
				textViewList.add(text);
				Log.i(bTAG, "TextViewList size " + textViewList.size());
			}
			int count = linearlayout.getChildCount();
			if (count > 12) {
				linearlayout.removeViewAt(count - 1);
			}
		} catch (Throwable t) {
			Log.e(TAG, Log.getStackTraceString(t));
		}
	}

	private void waitForEnable() {
		int timeoutCounter = 0;
		Log.i(bTAG, "SHOWING DIALOG");
		Log.i(bTAG, "TIMEOUT COUNTER STARTED");
		TestAdapter.enable();
		while (!TestAdapter.isEnabled() && timeoutCounter != 5000) {
			SystemClock.sleep(200);
			timeoutCounter += 200;
		}
		if (timeoutCounter == 5000) {
			// Currently, the timeout is set to close the activity completely
			finishScreenActivity("BLUETOOTH ADAPTER NOT RESPONDING... Closing Application");
		}
	}

	public void UpdateDevices(int numOfDevices) {
		NumDeviceText.setText(Integer.toString(numOfDevices));
	}

	public void finishScreenActivity(String dialogMessage) {
		dialog2 = new ProgressDialog(this);
		dialog2.setMessage(dialogMessage);
		dialog2.setCancelable(false);
		dialog2.show();
		new CountDownTimer(5000, 1000) {
			public void onTick(long millisUntilFinished) {
			}

			public void onFinish() {
				dialog2.dismiss();
				Intent locationServiceIntent = new Intent(FirstResponder.this,
						LocationService.class);
				LocationService.setServiceStatus(LocationService.PASSIVE_MODE);
				startService(locationServiceIntent);
				finish();
			}
		}.start();
	}

	public void resetTabColors() {
		for (int i = 0; i < tabColor.length - 1; i++) {
			tabColor[i] = greenishColor;
		}
		tabColor[7] = greenishBackgroundColor;
		tabColor[8] = greenishBackgroundColor;
		tabColor[9] = greenishBackgroundColor;
		alertTab.setBackgroundColor(greenishColor);
		routeTab.setBackgroundColor(greenishColor);
		apparatusTab.setBackgroundColor(greenishColor);
		prePlanTab.setBackgroundColor(greenishColor);
		adminTab.setBackgroundColor(greenishColor);
		mapTab.setBackgroundColor(Color.DKGRAY);
		directionsTab.setBackgroundColor(Color.DKGRAY);
		tabLayout.setBackgroundColor(greenishBackgroundColor);
		seeBluetoothScanningScreen.setBackgroundColor(greenishBackgroundColor);
		assetsButton.setBackgroundColor(greenishBackgroundColor);

	}

	public void updateTimerText(String text) {
		TimerText.setText(text);
	}

	// these methods are needed because you cannot release the audio files while
	// in a runnable.
	// exception will randomly occur without these because a media player
	// object might still be locked
	public void releaseMp() {
		mp.release();
	}

	public void releaseMp2() {
		mp2.release();
	}

	public Context getContext() {
		return FirstResponder.this;
	}

	private String[] getDirectionData(String srcPlace, String destPlace) {

		String urlString = "http://maps.google.com/maps?f=d&hl=en&saddr="
				+ srcPlace + "&daddr=" + destPlace
				+ "&ie=UTF8&0&om=0&output=kml";

		Log.d("URL", urlString);
		Document doc = null;
		HttpURLConnection urlConnection = null;
		URL url = null;
		String pathConent = "";
		try {
			url = new URL(urlString.toString());
			urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.setRequestMethod("GET");
			urlConnection.setDoOutput(true);
			urlConnection.setDoInput(true);
			urlConnection.connect();
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			doc = db.parse(urlConnection.getInputStream());
		} catch (Exception e) {
			Log.d(TAG, "couldn't parse url for getDirectionData() method");
		}
		try {
			NodeList nl = doc.getElementsByTagName("LineString");
			for (int s = 0; s < nl.getLength(); s++) {
				Node rootNode = nl.item(s);
				NodeList configItems = rootNode.getChildNodes();
				for (int x = 0; x < configItems.getLength(); x++) {
					Node lineStringNode = configItems.item(x);
					NodeList path = lineStringNode.getChildNodes();
					pathConent = path.item(0).getNodeValue();
				}
			}
		} catch (Throwable t) {
			Log.e(TAG, Log.getStackTraceString(t));
		}
		String[] tempContent = pathConent.split(" ");
		return tempContent;
	}

	private ArrayList<String> getDirectionPoints(String srcPlace,
			String destPlace) {
		String urlString = "http://maps.google.com/maps?f=d&hl=en&saddr="
				+ srcPlace + "&daddr=" + destPlace
				+ "&ie=UTF8&0&om=0&output=kml";
		Log.d("URL", urlString);
		Document doc = null;
		HttpURLConnection urlConnection = null;
		URL url = null;
		String pathConent = "";
		ArrayList<String> FullPathContent = new ArrayList<String>();
		try {
			url = new URL(urlString.toString());
			urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.setRequestMethod("GET");
			urlConnection.setDoOutput(true);
			urlConnection.setDoInput(true);
			urlConnection.connect();
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			doc = db.parse(urlConnection.getInputStream());
		} catch (Exception e) {
			Log.d(TAG, "couldn't parse url for getDirectionPoints() method");
		}
		try {
			NodeList nl = doc.getElementsByTagName("Point");
			for (int s = 0; s < nl.getLength(); s++) {
				Node rootNode = nl.item(s);
				NodeList configItems = rootNode.getChildNodes();
				for (int x = 0; x < configItems.getLength(); x++) {
					Node lineStringNode = configItems.item(x);
					NodeList path = lineStringNode.getChildNodes();

					pathConent = path.item(0).getNodeValue();
					Log.d("ZZZZZZZZZZZZ", pathConent + "\n");
					FullPathContent.add(pathConent);
				}
			}
			Log.d("TAG", FullPathContent.get(0) + "\n" + FullPathContent.get(1)
					+ "\n" + FullPathContent.get(2));
		} catch (Throwable t) {
			Log.e(TAG, Log.getStackTraceString(t));
		}
		return FullPathContent;
	}

	private ArrayList<String> getDirectionDataString(String srcPlace,
			String destPlace) {
		String urlString = "http://maps.google.com/maps?f=d&hl=en&saddr="
				+ srcPlace + "&daddr=" + destPlace
				+ "&ie=UTF8&0&om=0&output=kml";

		Log.d("URL", urlString);
		Document doc = null;
		HttpURLConnection urlConnection = null;
		URL url = null;
		String pathContent = "";
		ArrayList<String> FullPathContent = new ArrayList<String>();

		try {

			url = new URL(urlString.toString());
			urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.setRequestMethod("GET");
			urlConnection.setDoOutput(true);
			urlConnection.setDoInput(true);
			urlConnection.connect();
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			doc = db.parse(urlConnection.getInputStream());

		} catch (Exception e) {
			Log.d(TAG, "couldn't parse url for getDirectionDataString() method");
		}
		try {
			NodeList nl = doc.getElementsByTagName("name");
			for (int s = 0; s < nl.getLength(); s++) {
				Node rootNode = nl.item(s);
				NodeList configItems = rootNode.getChildNodes();
				pathContent = configItems.item(0).getNodeValue();
				FullPathContent.add(pathContent);
				Log.d(TAG, " " + pathContent);
			}
		} catch (Throwable t) {
			Log.e(TAG, Log.getStackTraceString(t));
		}
		return FullPathContent;
	}

	public void setResButtonStatus(boolean buttonStatus) {
		this.resButtonStatus = buttonStatus;
	}

	public void setNotResButtonStatus(boolean buttonStatus) {
		this.notResButtonStatus = buttonStatus;
	}

	public void saveBaseTime(long b) {
		saveBaseTime = b;
	}

	// public void bluetoothUpdateTextViewArray()
	// {
	// // Saves the current TextViews in the Bluetooth Logging Screen, This
	// // must be done before the onSavedInstanceState() call
	// savedTextViewList = (ArrayList<? extends Parcelable>) textViewList;
	// }
	public void saveReverseGeocodeAddress(String s) {
		Log.i(TAG, "saveReverseGeocodeAddress() called");
		reverseGeocodeAddress.add(s);
	}

	/**
	 * This method cleans current map and re-populates the map with the
	 * directions route, gets the directions and displays on the text subTab of
	 * Route.
	 */
	public void populateMapAndGetDirections(Location loc, Location des) {
		Log.i(TAG, "										() method called");
		try {
			// removes old overlays/route paths
			for (int i = 0; i < mapview.getOverlays().size(); i++) {
				mapview.getOverlays().clear();
			}
			GeoPoint currentLocation = new GeoPoint(
					(int) (loc.getLatitude() * 1e6),
					(int) (loc.getLongitude() * 1e6));
			GeoPoint destination = new GeoPoint(
					(int) (des.getLatitude() * 1e6),
					(int) (des.getLongitude() * 1e6));
			String pairs[] = getDirectionData(
					loc.getLatitude() + "," + loc.getLongitude(),
					des.getLatitude() + "," + des.getLongitude());
			ArrayList<String> directionsPairs = getDirectionPoints(
					loc.getLatitude() + "," + loc.getLongitude(),
					des.getLatitude() + "," + des.getLongitude());
			// these points are the ones where the text directions occur
			// append directions to UI
			textDirections = getDirectionDataString(loc.getLatitude() + ","
					+ loc.getLongitude(),
					des.getLatitude() + "," + des.getLongitude());
			ListView listview = new ListView(FirstResponder.this);
			// removes the "route" text at bottom
			textDirections.remove(textDirections.size() - 1);
			textDirections.remove(0);// removes the heading
			for (int i = 0; i < textDirections.size(); i++) {
				textDirections.set(i, (i + 1) + ") " + textDirections.get(i));
			}
			// Reverse Geocodes and adds the address of the current
			// location underneath inside the list view.
			textDirections.add(
					0,
					"Your current Location : \n"
							+ (mService.reverseGeoCode(loc)));

			listview.setAdapter(new ArrayAdapter<String>(FirstResponder.this,
					android.R.layout.simple_list_item_1, textDirections));
			AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
					ViewGroup.LayoutParams.FILL_PARENT, 600);
			listview.setLayoutParams(lp);
			if (directionsL.getChildCount() == 1) {
				directionsL.removeViewAt(0);
			}
			directionsL.addView(listview, 0);
			String[] lngLat = pairs[0].split(",");
			String[] directionsLngLat = directionsPairs.get(0).split(",");
			// STARTING POINT
			GeoPoint startGP = new GeoPoint(
					(int) (Double.parseDouble(lngLat[1]) * 1E6),
					(int) (Double.parseDouble(lngLat[0]) * 1E6));
			GeoPoint DirectionStartGP = new GeoPoint(
					(int) (Double.parseDouble(directionsLngLat[1]) * 1E6),
					(int) (Double.parseDouble(directionsLngLat[0]) * 1E6));
			myMC = mapview.getController();
			geoPoint = startGP;
			myMC.setCenter(geoPoint);
			myMC.setZoom(18);
			drawableStart = getResources().getDrawable(
					R.drawable.map_pin_current_location);
			DirectionPathOverlay itemizedOverlay = new DirectionPathOverlay(
					drawableStart, FirstResponder.this, startGP, startGP);
			OverlayItem overlayitem = new OverlayItem(currentLocation, "YOU",
					"You are here");
			itemizedOverlay.addOverlay(overlayitem);
			mapview.getOverlays().add(itemizedOverlay);
			// NAVIGATE THE PATH
			GeoPoint gp1;
			GeoPoint gp2 = startGP;
			// navigate the directions text points
			GeoPoint Dgp1;
			GeoPoint Dgp2 = DirectionStartGP;
			drawableStop = getResources().getDrawable(
					R.drawable.map_pin_destination);
			drawableMov = getResources().getDrawable(R.drawable.tinydot);
			for (int i = 1; i < pairs.length; i++) {
				lngLat = pairs[i].split(",");
				gp1 = gp2;
				// watch out! For GeoPoint, first:latitude,
				// second:longitude
				gp2 = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6),
						(int) (Double.parseDouble(lngLat[0]) * 1E6));
				NormalOverlay CurrentPath = new NormalOverlay(gp1, gp2);
				// this overlay has no markers.
				mapview.getOverlays().add(CurrentPath);
				Log.d(TAG, "pair:" + pairs[i]);
			}
			for (int i = 0; i < directionsPairs.size(); i++) {
				directionsLngLat = directionsPairs.get(i).split(",");
				Dgp1 = Dgp2;
				Dgp2 = new GeoPoint(
						(int) (Double.parseDouble(directionsLngLat[1]) * 1E6),
						(int) (Double.parseDouble(directionsLngLat[0]) * 1E6));
				DirectionPathOverlay CurrentPath = new DirectionPathOverlay(
						drawableMov, FirstResponder.this, Dgp1, Dgp1);
				OverlayItem overlayitemCurrent = new OverlayItem(Dgp2, "path",
						textDirections.get(i + 1));
				CurrentPath.addOverlay(overlayitemCurrent);
				mapview.getOverlays().add(CurrentPath);
				Log.d(TAG, "Directionspair:" + directionsPairs.get(i));
			}
			// END POINT
			DirectionPathOverlay itemizedOverlay2 = new DirectionPathOverlay(
					drawableStop, FirstResponder.this, gp2, gp2);
			OverlayItem overlayitemDest = new OverlayItem(destination, "END",
					"Your Destination");
			itemizedOverlay2.addOverlay(overlayitemDest);
			mapview.getOverlays().add(itemizedOverlay2);
			Log.d("loookatOverlaysize", " " + mapview.getOverlays().size());
			mapview.getController().animateTo(startGP);
			mapview.setBuiltInZoomControls(true);
			mapview.displayZoomControls(true);
		} catch (Throwable t) {
			Log.e(TAG, Log.getStackTraceString(t));
		}
	}
}

class HelloWebViewClient extends WebViewClient {
	@Override
	public boolean shouldOverrideUrlLoading(WebView view, String url) {
		view.loadUrl(url);
		return true;
	}
}